// Copyright 2013 The Walk Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package winFrom

import (
	"fmt"
	"strings"
	//"log"
	//"time"
)

import (
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

func RunAddUrlDialog(mw *MyMainWindow) (int, error) { //walk.Form
	var dlg *walk.Dialog
	//var db *walk.DataBinder
	//var ep walk.ErrorPresenter
	var ep walk.ErrorPresenter
	var acceptPB, cancelPB *walk.PushButton
	owner := walk.Form(mw)
	var te *walk.TextEdit
	return Dialog{
		AssignTo:      &dlg,
		Title:         "添加url",
		DefaultButton: &acceptPB,
		CancelButton:  &cancelPB,

		MinSize: Size{500, 300},
		Layout:  VBox{},
		Children: []Widget{
			Composite{
				Layout: Grid{},
				Children: []Widget{
					Label{
						Row:    0,
						Column: 0,
						Text:   "多行url以;隔开",
					},

					TextEdit{
						Row:        2,
						Column:     0,
						ColumnSpan: 5,
						AssignTo:   &te,
					},

					LineErrorPresenter{
						AssignTo:   &ep,
						Row:        5,
						Column:     0,
						ColumnSpan: 2,
					},
				},
			},
			Composite{
				Layout: HBox{},
				Children: []Widget{
					HSpacer{},
					PushButton{
						AssignTo: &acceptPB,
						Text:     "添加任务队列",
						OnClicked: func() {
							fmt.Println(te.Text())
							urlList := strings.Split(te.Text(), ";")
							for _, str := range urlList {
								var tb Tb_url

								if tb.IfExsitesRow(`select * from Tb_url where  url= '`+str+`'`) == 0 {
									tb.ExecUrlListSql(`insert into  Tb_url(url,isDownload)
							values('` + str + `',-1) `)
									//mw.Urlmodel.Ini_Tb_url_Clear(`select urlid,url,isDownload,startTime,endTime from Tb_url
									//where  url= '` + str + `'`)
									mw.Urlmodel.ResetRows()
								} else {
									RunDialogOKCancel_URL_RDownload(mw, str)
								}

								dlg.Accept()
							}
						},
					},
					PushButton{
						AssignTo:  &cancelPB,
						Text:      "取消",
						OnClicked: func() { dlg.Cancel() },
					},
				},
			},
		},
	}.Run(owner)
}
